package com.beek.android.jim;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsMessage;
import android.widget.Toast;

import com.beek.android.jim.Util;

public class SmsReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    // ---get the SMS message passed in---
    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs = null;
    String phonenum = "";
    String textmsg = "";
    if (bundle != null) {
      // ---retrieve the SMS message received---
      Object[] pdus = (Object[]) bundle.get("pdus");
      msgs = new SmsMessage[pdus.length];
      for (int i = 0; i < msgs.length; i++) {
        msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
        phonenum = msgs[i].getOriginatingAddress();
        textmsg = msgs[i].getMessageBody().toString();
        if (checkReceivedSMS(context, phonenum, textmsg)) {
          abortBroadcast();
        }
        ;
      }
    }
  }

  private boolean checkReceivedSMS(Context context, String phonenum, String textmsg) {
    boolean StopBroadcast = false;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    // stop broadcast of confirmation messages
    if ((textmsg.contains("JIM Mobile")) && (textmsg.contains("We hebben je aanvraag goed ontvangen"))) {
      StopBroadcast = true;
    }
    if ((textmsg.contains("JIM Mobile")) && (textmsg.contains("Nous avons bien recu ta demande."))) {
      StopBroadcast = true;
    }

    // Data expired -- only nl --- TODO:fr (text ?)
    if (textmsg.contains("De datum van uw datategoed voor WAP & mobiel internet is voorbij.")) {
      storeBalance(context, "data", "0 kB", "", "0");

      switch (prefs.getString("automateDataAtExpiry", "N").charAt(0)) {
      case 'R':
        sendSMS(context, "MEGASURF"); // Rebuy a data bundle
        break;
      case 'D':
        Util.SetDataConnection(context, false); // stop data
      }
    }

    // Data used up -- only nl --- TODO:fr (text ?)
    if (textmsg.contains("Uw datategoed is opgebruikt, u betaalt nu per kilobyte.")) {
      storeBalance(context, "data", "0 kB", "", "0");

      switch (prefs.getString("automateDataAtUse", "N").charAt(0)) {
      case 'R':
        sendSMS(context, "MEGASURF"); // Rebuy a data bundle
        break;
      case 'D':
        Util.SetDataConnection(context, false); // stop data
      }
    }

    // Data bought -- only nl --- TODO:fr (text ?)
    if (textmsg.contains("Beste klant, jouw aankoop van 500 MB was succesvol")) {
      String datTot = textmsg.substring(textmsg.indexOf("geldig tot ") + 11, textmsg.indexOf("geldig tot ") + 21);
      String balanceTxt = "512000 kB tot " + datTot;
      storeBalance(context, "data", balanceTxt, datTot, "512000");
      StopBroadcast = true;
    }

    // -- BELTEGOED nl
    // Beste klant. U heeft nog 2.08 EUR geldig tot en met 24/12/2012. Groet, BASE.
    // Beste klant. U heeft nog
    if ((textmsg.indexOf("Beste klant. U heeft nog ") >= 0) && (textmsg.indexOf(" EUR geldig tot en met ") >= 0)) {
      String beltegoed = Util.StringBetween(textmsg, "U heeft nog ", " EUR geldig tot en met");
      String dateTo = Util.StringBetween(textmsg, " tot en met ", ". Groet, BASE.");
      storeBalance(context, "beltegoed", beltegoed + " EUR tegoed tem " + dateTo, dateTo, beltegoed);
      StopBroadcast = true;
    }

    // -- BELTEGOED fr
    if (textmsg.contains("Cher Client. Il vous reste ") && textmsg.contains(" EUR valables jusqu'au ")) {
      String beltegoed = Util.StringBetween(textmsg, "Il vous reste ", " EUR valables jusqu");
      String dateTo = Util.StringBetween(textmsg, " EUR valables jusqu'au ", ". Bien a vous, BASE.");
      storeBalance(context, "beltegoed", beltegoed + " EUR tegoed tem " + dateTo, dateTo, beltegoed);
      StopBroadcast = true;
    }

    Resources res = context.getResources();
    String[] baltype = res.getStringArray(R.array.baltype);
    String[] match = res.getStringArray(R.array.match);
    String[] before = res.getStringArray(R.array.before);
    String[] after = res.getStringArray(R.array.after);
    String[] txt = res.getStringArray(R.array.txt);

    for (int i = 0; i < baltype.length; i++) {
      if (checkBaseMsg(context, textmsg, baltype[i], match[i * 2], before[i * 2], after[i * 2], txt[i * 2])) {
        StopBroadcast = true;
      }
      if (checkBaseMsg(context, textmsg, baltype[i], match[i * 2 + 1], before[i * 2 + 1], after[i * 2 + 1],
          txt[i * 2 + 1])) {
        StopBroadcast = true;
      }
    }

    return StopBroadcast;
  }

  private boolean checkBaseMsg(Context context, String textmsg, String baltype, String match, String before,
      String after, String txt) {
    if (textmsg.matches(match)) {
      String value = Util.StringBetween(textmsg, before, after);
      String datTot = textmsg.substring(textmsg.indexOf(after) + after.length(),
          textmsg.indexOf(after) + after.length() + 10);
      String balanceTxt = value + txt + datTot;
      storeBalance(context, baltype, balanceTxt, datTot, value);
      return true;
    }
    return false;
  }

  // ---sends an SMS message to another device---
  private void sendSMS(Context context, String message) {
    Intent sendSMSIntent = new Intent(context, MainService.class);
    sendSMSIntent.setAction("com.beek.android.jim.sendsms");
    sendSMSIntent.putExtra("Type", "");
    sendSMSIntent.putExtra("Message", message);
    context.startService(sendSMSIntent);
  }

  // ---store balance into Preferences file---
  private void storeBalance(Context context, String key, String txt, String dateTo, String value) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences balances = context.getSharedPreferences("balances", 0);
    SharedPreferences.Editor editor = balances.edit();
    editor.putString(key + "_txt", txt);
    editor.putString(key + "_value", value);
    editor.putString(key + "_dateTo", dateTo);
    editor.commit();
    if (!prefs.getBoolean("noToastsFromJim", false)) {
      Toast.makeText(context, txt, Toast.LENGTH_SHORT).show();
    }
    context.sendBroadcast(new Intent("update_jimRED_balances_screen"));
  }
}
